<template>
  <div class="min-h-screen bg-gradient-to-br from-blue-50 to-indigo-100 flex items-center justify-center p-4">
    <div class="max-w-md w-full">
      <!-- Logo -->
      <div class="text-center mb-8">
        <div class="inline-flex items-center justify-center w-16 h-16 bg-indigo-600 rounded-full mb-4">
          <i class="fas fa-user text-white text-2xl"></i>
        </div>
        <h1 class="text-3xl font-bold text-gray-900 mb-2">欢迎回来</h1>
        <p class="text-gray-600">请登录您的账户</p>
      </div>

      <!-- Login Form -->
      <div class="bg-white rounded-2xl shadow-xl p-8">
        <form @submit.prevent="handleSubmit" class="space-y-6">
          <!-- Username -->
          <div>
            <label for="username" class="block text-sm font-medium text-gray-700 mb-2">
              用户名
            </label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <i class="fas fa-user text-gray-400"></i>
              </div>
              <input
                id="username"
                v-model="form.username"
                type="text"
                class="w-full pl-10 pr-3 py-3 border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
                :class="{
                  'border-red-300': errors.username,
                  'border-gray-300': !errors.username
                }"
                placeholder="请输入用户名"
              />
            </div>
            <p v-if="errors.username" class="mt-1 text-sm text-red-600">
              {{ errors.username }}
            </p>
          </div>

          <!-- Password -->
          <div>
            <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
              密码
            </label>
            <div class="relative">
              <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <i class="fas fa-lock text-gray-400"></i>
              </div>
              <input
                id="password"
                v-model="form.password"
                :type="showPassword ? 'text' : 'password'"
                class="w-full pl-10 pr-10 py-3 border rounded-lg focus:ring-2 focus:ring-indigo-500 focus:border-indigo-500 transition-colors"
                :class="{
                  'border-red-300': errors.password,
                  'border-gray-300': !errors.password
                }"
                placeholder="请输入密码"
              />
              <button
                type="button"
                @click="showPassword = !showPassword"
                class="absolute inset-y-0 right-0 pr-3 flex items-center"
              >
                <i :class="showPassword ? 'fas fa-eye-slash' : 'fas fa-eye'" 
                   class="text-gray-400 hover:text-gray-600"></i>
              </button>
            </div>
            <p v-if="errors.password" class="mt-1 text-sm text-red-600">
              {{ errors.password }}
            </p>
          </div>

          <!-- Remember me -->
          <div class="flex items-center justify-between">
            <label class="flex items-center">
              <input
                type="checkbox"
                v-model="form.remember"
                class="rounded border-gray-300 text-indigo-600 focus:ring-indigo-500"
              />
              <span class="ml-2 text-sm text-gray-600">记住我</span>
            </label>
            <a href="#" class="text-sm text-indigo-600 hover:text-indigo-500">
              忘记密码？
            </a>
          </div>

          <!-- Error Message -->
          <div v-if="authStore.error" 
               class="bg-red-50 border border-red-200 rounded-lg p-3">
            <p class="text-sm text-red-600 text-center">
              <i class="fas fa-exclamation-circle mr-1"></i>
              {{ authStore.error }}
            </p>
          </div>

          <!-- Success Message -->
          <div v-if="successMessage" 
               class="bg-green-50 border border-green-200 rounded-lg p-3">
            <p class="text-sm text-green-600 text-center">
              <i class="fas fa-check-circle mr-1"></i>
              {{ successMessage }}
            </p>
          </div>

          <!-- Submit Button -->
          <button
            type="submit"
            :disabled="authStore.isLoading || !isFormValid"
            class="w-full py-3 px-4 bg-indigo-600 hover:bg-indigo-700 disabled:bg-gray-300 disabled:cursor-not-allowed text-white font-medium rounded-lg transition-colors duration-200"
          >
            <span v-if="!authStore.isLoading">登录</span>
            <span v-else class="flex items-center justify-center">
              <i class="fas fa-spinner fa-spin mr-2"></i>
              登录中...
            </span>
          </button>
        </form>

        <!-- Demo Info -->
        <div class="mt-6 text-center">
          <p class="text-sm text-gray-500">
            演示账号：admin / 123456
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { useAuthStore } from '../stores/auth'

const authStore = useAuthStore()
const showPassword = ref(false)
const successMessage = ref('')

const form = reactive({
  username: '',
  password: '',
  remember: false
})

const errors = reactive({
  username: '',
  password: ''
})

// 表单验证
const validateForm = () => {
  let isValid = true
  
  // 验证用户名
  if (!form.username.trim()) {
    errors.username = '请输入用户名'
    isValid = false
  } else if (form.username.length < 3) {
    errors.username = '用户名至少3个字符'
    isValid = false
  } else {
    errors.username = ''
  }
  
  // 验证密码
  if (!form.password) {
    errors.password = '请输入密码'
    isValid = false
  } else if (form.password.length < 6) {
    errors.password = '密码至少6个字符'
    isValid = false
  } else {
    errors.password = ''
  }
  
  return isValid
}

// 计算表单是否有效
const isFormValid = computed(() => {
  return form.username.trim().length >= 3 && 
         form.password.length >= 6 && 
         !authStore.isLoading
})

// 监听表单变化，实时验证
watch(() => form.username, () => {
  if (form.username.trim() && form.username.length >= 3) {
    errors.username = ''
  }
})

watch(() => form.password, () => {
  if (form.password && form.password.length >= 6) {
    errors.password = ''
  }
})

// 处理提交
const handleSubmit = async () => {
  if (!validateForm()) return
  
  const result = await authStore.login({
    username: form.username,
    password: form.password
  })
  
  if (result.success) {
    successMessage.value = result.message
    // 2秒后清除成功消息
    setTimeout(() => {
      successMessage.value = ''
    }, 2000)
    
    // 如果选择了记住我，保存到本地存储
    if (form.remember) {
      localStorage.setItem('rememberedUsername', form.username)
    }
  }
}

// 初始化时检查是否有记住的用户名
const initRememberedUsername = () => {
  const remembered = localStorage.getItem('rememberedUsername')
  if (remembered) {
    form.username = remembered
    form.remember = true
  }
}

initRememberedUsername()
</script>
